package shop.controller.front.account;

import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import shop.core.FrontBaseController;
import shop.core.Services;
import shop.core.common.bean.*;
import shop.core.plugins.sms.SMS;
import shop.core.plugins.sms.SMSVerifyCodeResult;
import shop.core.util.MD5;
import shop.core.util.WxUtil;
import shop.services.front.account.AccountService;
import shop.services.front.account.bean.Account;
import shop.services.front.offlineAccount.OfflineAccountService;
import shop.services.front.offlineAccount.bean.OfflineAccount;
import shop.services.front.organize.OrganizeService;
import shop.services.front.organize.bean.Organize;
import shop.services.manage.system.bean.User;
import shop.services.manage.system.impl.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 志愿者
 * Created by Administrator on 2017/4/17.
 */
@Controller
@RequestMapping("/front/account")
public class AccountController extends FrontBaseController<Account> {
    @Resource
    private AccountService accountService;
    @Resource
    private OrganizeService organizeService;
    @Resource
    private UserService userService;
    @Resource
    private OfflineAccountService offlineAccountService;

    @Override
    public Services<Account> getService() {
        return accountService;
    }


    /**
     * 跳转到我列表页面方法
     */
    @RequestMapping("/toAccountList")
    public String toAccountList() {
        return "/front/account/accountList";
    }

    /**
     * 跳转到志愿者认证页面
     */
    @RequestMapping("/toAccountEdit")
    public String toAccountEdit() {
        return "/front/account/accountEdit";
    }

    /**
     * 跳转到机构认证页面
     */
    @RequestMapping("/toOrganizeEdit")
    public String toOrganizeEdit() {
        return "/front/account/organizeEdit";
    }

    /**
     * 跳转到设置页面
     */
    @RequestMapping("/toSet")
    public String toSet() {
        return "/front/account/set";
    }

    /**
     * 跳转到我的活动列表
     */
    @RequestMapping("/toAccountOfflineList")
    public String toAccountOfflineList() {
        return "/front/account/accountOfflineList";
    }

    /**
     * 跳转到我发布的活动列表
     */
    @RequestMapping("/toMyIssue")
    public String toMyIssue() {
        return "/front/account/organizeOfflineList";
    }

    /**
     * 跳转到我的机构方法（志愿者）
     */
    @RequestMapping("/toMyOrganize")
    public String toMyOrganize() {
        return "/front/account/myOrganize";
    }

    /**
     * 跳转到我的所属机构（机构账号）
     */
    @RequestMapping("/toMySub")
    public String toMySub() {
        return "/front/account/mySub";
    }

    /**
     * 跳转到找组织页面
     * @return
     */
    @RequestMapping("/toFindOrganize")
    public String toFindOrganize() {
        return "/front/account/findOrganize";
    }

    /**
     * 跳转到机构详情页面
     */
    @RequestMapping("/toOrganizeDetail")
    public String toOrganizeDetail() {
        return "/front/account/organizeDetail";
    }

    /**
     * 跳转到我的排行榜页面
     * @return
     */
    @RequestMapping("/toAccountRank")
    public String toAccountRank() {
        return "/front/account/accountRank";
    }

    /**
     * 跳转到机构注册页面（微信）
     * @return
     */
    @RequestMapping("/toOrganizeRegister")
    public String toOrganizeRegister() {
        return "/front/organize/organizeRegister";
    }

    /**
     * 跳转到登陆页面（微信）
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "/front/login";
    }


    /**
     * 跳转到修改密码页面
     */
    @RequestMapping("/toUpdatePwd")
    public String toUpdatePwd() {
        return "/front/account/updatePwd";
    }

    /**
     * 跳转到忘记密码页面
     * @return
     */
    @RequestMapping("/toForgetPassword")
    public String toForgetPassword() {
        return "/front/forgetPassword";
    }

    /**
     * 跳转到志愿者注册页面
     * @return
     */
    @RequestMapping("/toVolunteerRegister")
    public String toVolunteerRegister() {
        return "/front/account/volunteerRegister";
    }


    /**
     * 志愿者认证方法
     *
     * @param request
     * @param account
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/accountAut", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult accountAut(HttpServletRequest request, @ModelAttribute("account") Account account) throws IllegalAccessException {
        jsonResult = new JSONResult();
        Account rs = (Account) request.getSession().getAttribute("accountInfo");
        switch (rs.getStatus()) {
            case "0":
                jsonResult.setMessage("您已进行过认证操作，请耐心等待审核结果！");
                jsonResult.setSuccess(false);
                return jsonResult;
            case "1":
                jsonResult.setMessage("您已通过审核，无需再进行认证操作！");
                jsonResult.setSuccess(false);
                return jsonResult;
            case "2":
                account.setStatus("0");
                getService().update(account);
                return jsonResult;
            default:
                account.setStatus("0");
                getService().update(account);
                return jsonResult;
        }


    }

    /**
     * 志愿者加入机构方法（找组织）
     *
     * @param request
     * @param account
     * @return
     * @throws Exception
     */
    @Override
    @RequestMapping(value = "/updateJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateJson(HttpServletRequest request, @ModelAttribute("account") Account account) throws Exception {
        jsonResult = new JSONResult();
        Account rs = (Account) request.getSession().getAttribute("accountInfo");
        if(rs.getStatus().equals("1")){//判断志愿者是否通过审核
            if (!StringUtils.isBlank(rs.getOrganizeID())) {
                jsonResult.setMessage("志愿者只能加入一个机构，请先退出当前机构！");//限制志愿者加入多个机构
                jsonResult.setSuccess(false);
                return jsonResult;
            } else {
                Organize organize = new Organize();
                organize.setId(account.getOrganizeID());
                organize = organizeService.selectOne(organize);
                getService().update(account);
                rs.setOrganizeID(account.getOrganizeID());
                request.getSession().setAttribute("accountInfo", rs);
                organize.setAccountNum(organize.getAccountNum() + 1);
                organizeService.update(organize);
                return jsonResult;
            }
        }else{
            jsonResult.setMessage("您还未通过审核，无法加入机构！");
            jsonResult.setSuccess(false);
            return jsonResult;
        }
    }

    /**
     * 查询单个机构方法
     */
    @RequestMapping(value = "/selectOrganizeDetail", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectOrganizeDetail(Organize organize) {
        organize = organizeService.selectOne(organize);
        jsonResult = new JSONResult();
        jsonResult.setData(organize);
        return jsonResult;
    }

    /**
     * 机构认证方法
     *
     * @throws Exception
     */
    @RequestMapping(value = "/updateOrganizeJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateOrganizeJson(HttpServletRequest request, Organize organize) throws Exception {
        jsonResult = new JSONResult();
        User user = (User) request.getSession().getAttribute("userInfo");
        Organize rs = new Organize();
        rs.setPrincipalPhone(user.getUsername());
        rs = organizeService.selectOne(rs);
        if (rs.getStatus().equals("0")) {
            jsonResult.setMessage("该机构已进行过认证操作，请耐心等待审核结果！");
            jsonResult.setSuccess(false);
            return jsonResult;
        } else if (rs.getStatus().equals("1")) {
            jsonResult.setMessage("该机构已通过审核，无需再进行认证操作！");
            jsonResult.setSuccess(false);
            return jsonResult;
        } else {
            organize.setStatus("0");
            organizeService.update(organize);
            return jsonResult;
        }
    }

    /**
     * 退出机构方法
     *
     * @param account
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updateAccountJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateAccountJson(HttpServletRequest request, Account account) throws Exception {
        jsonResult = new JSONResult();
        Account rs = (Account) request.getSession().getAttribute("accountInfo");
        Organize organize = new Organize();
        organize.setId(rs.getOrganizeID());
        organize = organizeService.selectOne(organize);
        account.setOrganizeID("");
        accountService.update(account);
        organize.setAccountNum(organize.getAccountNum() - 1);
        organizeService.update(organize);
        return jsonResult;
    }

    /**
     * 修改机构密码方法
     *
     * @throws Exception
     */
    @RequestMapping(value = "/updateUserJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateUserJson(HttpServletRequest request, String oldPwd, String newPwd) throws Exception {
        jsonResult = new JSONResult();
        if(StringUtils.isBlank(oldPwd)||StringUtils.isBlank(newPwd)){
            jsonResult.setMessage("信息不完整，请填写完整后重试！");
            jsonResult.setSuccess(false);
            return jsonResult;
        }else {
            User rs = (User) request.getSession().getAttribute("userInfo");
            oldPwd = MD5.md5(oldPwd);
            newPwd = MD5.md5(newPwd);
            if (rs.getPassword().equals(oldPwd)) {
                rs.setPassword(newPwd);
                userService.update(rs);
                return jsonResult;
            } else {
                jsonResult.setMessage("原密码错误，请重新输入！");
                jsonResult.setSuccess(false);
                return jsonResult;
            }
        }
    }

    /**
     * 修改志愿者密码方法
     *
     * @throws Exception
     */
    @RequestMapping(value = "/updateAccountPwdJson", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult updateAccountPwdJson(HttpServletRequest request, String oldPwd, String newPwd) throws Exception {
        jsonResult = new JSONResult();
        if(StringUtils.isBlank(oldPwd)||StringUtils.isBlank(newPwd)){
            jsonResult.setMessage("信息不完整，请填写完整后重试！");
            jsonResult.setSuccess(false);
            return jsonResult;
        }else {
            Account account = (Account) request.getSession().getAttribute("accountInfo");
            oldPwd = MD5.md5(oldPwd);
            newPwd = MD5.md5(newPwd);
            if (account.getPassword().equals(oldPwd)) {
                account.setPassword(newPwd);
                accountService.update(account);
                return jsonResult;
            } else {
                jsonResult.setMessage("原密码错误，请重新输入！");
                jsonResult.setSuccess(false);
                return jsonResult;
            }
        }
    }

    /**
     * 查看我的机构方法（志愿者）
     */
    @RequestMapping(value = "/selectMyOrganize", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectMyOrganize(String id) {
        Account account = accountService.selectById(id);
        jsonResult = new JSONResult();
        jsonResult.setData(account);
        return jsonResult;
    }

    /**
     * 查看我的机构方法（机构账号）
     *
     * @throws Exception
     */
    @RequestMapping("/selectSubList")
    @ResponseBody
    public JSONResult selectSubList(Organize organize) throws Exception {
        List<Organize> rsList = organizeService.selectSubList(organize);
        jsonResult = new JSONResult();
        jsonResult.setData(rsList);
        return jsonResult;
    }

    /**
     * 查看我的活动（志愿者）
     */
    @RequestMapping(value = "/selectMyOffline", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectMyOffline(OfflineAccount offlineAccount) {
        JSONResult jsonResult = new JSONResult();
        List<OfflineAccount> list = offlineAccountService.selectList(offlineAccount);
        jsonResult.setData(list);
        jsonResult.setSuccess(true);
        return jsonResult;
    }

    /**
     * 登录成功跳转
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String loginSys(HttpSession session, HttpServletRequest request) {
        String code = request.getParameter("code");
        Map<String, String> params = new HashMap<>();
        params.put("appid", WxContainer.appid);
        params.put("secret", WxContainer.secret);
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        AccessToken accessToken = WxUtil.sendRequest(WxUrlType.accessTokenUrl, HttpMethod.GET, params, null, AccessToken.class);
        Map<String, String> getUserInfoParams = new HashMap<>();
        getUserInfoParams.put("access_token", accessToken.getAccess_token());
        getUserInfoParams.put("openid", accessToken.getOpenid());
        getUserInfoParams.put("lang", "zh_CN");
        Map<String, String> r = WxUtil.sendRequest(WxUrlType.userInfoUrl, HttpMethod.GET, getUserInfoParams, null, Map.class);
        logger.debug("微信登录返回信息：" + r);
        String openID = accessToken.getOpenid();
        session.setAttribute("userOpenId", openID);
        Account account = accountService.selectByOpenId(openID);
        User user = userService.selectByOpenId(accessToken.getOpenid());
        if (account != null) {
            session.setAttribute("accountInfo", account);
            logger.debug(session.getAttribute("accountInfo").toString());
            if (r.get("headimgurl") != null) {
                account.setHeadimgurl(r.get("headimgurl"));
            }
            accountService.update(account);
            return "redirect:/toHome";
        } else if (user != null) {
            Organize organize = new Organize();
            organize.setPrincipalPhone(user.getUsername());
            organize = organizeService.selectByPrincipalPhone(organize);
            session.setAttribute("userInfo", user);
            session.setAttribute("organizeInfo", organize);
            return "redirect:/toHome";
        } else {
            return "redirect:/";
        }
    }

    /**
     * 微信登录
     */
    @RequestMapping(value = "/go", method = RequestMethod.GET)
    public String goWx() {
        String appidUrl = "?appid=wx9dcac60230d12fbe&";
        String redirect_uri = "redirect_uri=http://www.kekelvxing.cn/front/account/login&";
        String typeUrl = "response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        return "redirect:" + WxUrlType.authorizeUrl + appidUrl + redirect_uri + typeUrl;
    }

    /**
     * 发送验证码
     *
     * @throws Exception
     */
    @RequestMapping(value = "/getSMSCode", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult getSMSCode(HttpServletRequest request) throws Exception {
        JSONResult rs = new JSONResult();
        String mobile = request.getParameter("mobile");
        List<User> userList= userService.selectList(new User());
        List<Account> accountList=accountService.selectList(new Account());
        for(User userInfo : userList){
            if(userInfo.getUsername().equals(mobile)){
                rs.setSuccess(false);
                rs.setMessage("该账号已注册过机构，不能重复注册！");
                return rs;//结束语句
            }
        }
        for(Account accountInfo : accountList){
            if(accountInfo.getPhone().equals(mobile)){
                rs.setSuccess(false);
                rs.setMessage("该账号已注册过志愿者，不能重复注册！");
                return rs;//结束语句
            }
        }
        SMS sms = new SMS();
        rs.setData(sms.sendCode(mobile, "5kDaOD-SQ8AbS959Lb9QRE", "86", null, null));//发送验证码方法
        rs.setSuccess(true);
        return rs;
    }

    /**
     * 校验验证码
     *
     * @throws Exception
     */
    @RequestMapping(value = "/checkCode", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult checkCode(HttpServletRequest request) throws Exception {
        JSONResult jsonResult = new JSONResult();
        String smsId = request.getParameter("SmsId");
        String smsContent = request.getParameter("SmsContent");
        SMS sms = new SMS();
        SMSVerifyCodeResult rs = sms.verifyCode(smsId, smsContent);//验证码验证方法
        if (rs.getSuccess() == null || !rs.getSuccess()) {
            jsonResult.setSuccess(false);
            jsonResult.setMessage("短信验证码错误！");
        } else {
            jsonResult.setSuccess(true);
        }
        return jsonResult;
    }


    /**
     * 重置密码（忘记密码）
     *
     * @throws Exception
     */
    @RequestMapping(value = "/resetPassword", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult resetPassword(String username, String password) throws Exception {
        jsonResult = new JSONResult();
        User user = new User();
        user.setUsername(username);
        Account account = new Account();
        account.setPhone(username);
        User rs = userService.selectOne(user);
        Account rs2 = accountService.selectByPhone(account);
        if (rs != null) {//通过账号查询该用户
            rs.setPassword(MD5.md5(password));
            userService.update(rs);
            return jsonResult;
        } else if (rs2 != null) {//通过账号（手机）查询该用户
            rs2.setPassword(MD5.md5(password));
            accountService.update(rs2);
            return jsonResult;
        } else {
            jsonResult.setMessage("账号错误，请重新输入！");
            jsonResult.setSuccess(false);
            return jsonResult;
        }
    }


    /**
     * 查询捐助排行
     */
    @RequestMapping(value = "/selectRank", method = RequestMethod.GET)
    @ResponseBody
    public JSONResult selectRank(Account account) {
        JSONResult rs = new JSONResult();
        List<Account> accountList = accountService.selectList(account);
        for (int i = 0; i < accountList.size(); i++) {
            if (accountList.get(i).getId().equals(account.getId())) {
                accountList.get(i).setAccountRank(i + 1);
            }
        }
        rs.setData(accountList);
        rs.setSuccess(true);
        return rs;
    }

    /**
     * 志愿者注册
     */
    @RequestMapping(value = "/insertAccount", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult insertAccount(HttpServletRequest request, @ModelAttribute("e") Account account, String content) throws Exception {
        JSONResult result = new JSONResult();
        // SmsId 短信唯一码   SmsContent 短信内容
        String smsId = request.getParameter("SmsId");
        String smsContent = request.getParameter("SmsContent");
        SMS sms = new SMS();
        SMSVerifyCodeResult rs = sms.verifyCode(smsId, smsContent);//验证验证码
        if (rs.getSuccess() == null || !rs.getSuccess()) {
            result.setSuccess(false);
            result.setMessage("短信验证码错误！");
            return result;
        }
        account.setPassword(MD5.md5(account.getPassword()));
        List<User> userList = userService.selectList(new User());
        List<Account> accountList = getService().selectList(new Account());
        for (User anUserList : userList) {//循环遍历userList
            if (anUserList.getUsername().equals(account.getPhone())) {
                result.setSuccess(false);
                result.setMessage("该手机已注册为机构，不允许注册为志愿者");
                return result;
            }
        }
        for (Account anAccountList : accountList) {//循环遍历accountList
            if (anAccountList.getPhone().equals(account.getPhone())) {
                result.setSuccess(false);
                result.setMessage("该手机已注册为志愿者，不可注册为机构");
                return result;
            }
        }
        accountService.insert(account);
        result.setSuccess(true);
        return result;
    }

    /**
     * 志愿者登录
     *
     * @param account 登录志愿者
     * @return 成功时返回志愿者信息 失败时返回失败信息
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public JSONResult login(Account account, HttpSession session) {
        JSONResult rs = new JSONResult();
        if (StringUtils.isBlank(account.getPhone()) || StringUtils.isBlank(account.getPassword())) {
            rs.setMessage("账户和密码不能为空!");
            rs.setSuccess(false);
            return rs;
        }
        logger.info("用户登录:{}", account.getPhone());
        account.setPassword(MD5.md5(account.getPassword()));
        Account u = accountService.login(account);
        if (u == null) {
            rs.setMessage("登陆失败，账户或密码错误！");
            rs.setSuccess(false);
            logger.error("登陆失败，账户或密码错误,{}", account.getPhone());
            return rs;
        }
        session.setAttribute("accountInfo", u);
        if (session.getAttribute("userOpenId") != null) {
            if(!StringUtils.isBlank(u.getopenID())&&!u.getopenID().equals(session.getAttribute("userOpenId").toString())){
                rs.setMessage("该微信号已与其他账号绑定，登录失败");
                rs.setSuccess(false);
                return rs;
            }
            u.setopenID(session.getAttribute("userOpenId").toString());
            accountService.update(u);
        }
        rs.setData(u);
        rs.setMessage("登录成功");
        rs.setSuccess(true);
        return rs;
    }
}